# This is the job submission script to resample the AWAP ASCII files of daily max and min temp
# To 250 m resolution for the WT plus Buffer regions

#########

# For now, subset micro to days <20090602 and run this

# Establish in directory

in.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/ToAnalyse/'
setwd(in.dir)

# Read in .csv file with days

micro = read.csv(paste(in.dir,'micro_min_max_static_xy.csv',sep=''),header=T)
micro=micro[which(micro$date<20090602),] # Get the rest of the tmax, tmin, and realrad files then delete this line and run again

# Create list of unique days

days.list = sort(unique(micro$date))


# Establish a temporary directory to write out the .sh files and .Rout files to
# This keeps your workspace more orderly and should the script fuck up all error logs will be stored in one location

tmp.pbs = '/home1/99/jc152199/tmp.pbs/'
setwd(tmp.pbs)

# Input location of the script to be run by this batch script

script.file = '/home1/99/jc152199/MicroclimateStatisticalDownscale/dailyspatialextracts/2run.r'

# Begin a loop to create an .sh  file for each AWAP layer to be resample and then submit the jobs to the HPC

for(dayx in days.list) 

	{
	
	tname = paste(dayx,'.sh',sep='') #Create a name for the .sh file for each element (dayx) in days.list
	
	arg.dayx = paste('dayx="',dayx,'" ',sep='') # Define the argument for dayx 
	
	zz = file(tname,'w') # This command creates a file with the name 'tname' The 'w' command opens the file and writes the following lines of text into it
		
		cat('##################################\n',file=zz) # First blank line of .sh file ### Note the use of '\n', any text following this will be on the next line
		cat('#!/bin/sh\n',file=zz) # First command line for HPC
		cat('cd $PBS_O_WORKDIR\n',file=zz) # Sets the directory to write out summary files at the above directory 'tmp.pbs'
		cat("R CMD BATCH --no-save --no-restore '--args ",arg.dayx,"' ",script.file,' ',gsub('.sh','',tname),'.Rout \n',sep='',file=zz) # This line tells R not to save to the .Rdata file and also not to restore the environment from the .Rdata file, very important when batching or you will get multiple fuckups, also defines the arguments, says where script to run is located, and defines the name for the R.out file
		cat('##################################\n',file=zz) # Last blank line of .sh file
		
	close(zz) # Closes the .sh file that you've just written
		
	cat('\n',dayx)
	
	# The follow line submits the job to the HPC, leave it commented out until you're ready to RUN all the jobs\
	# Always run the script first without removing the comment, this will still generate the .sh files for you to check before running
	# Once you're happy with that then submit a single .sh file and make sure it runs through to completion before batching out the rest with the following line
	system(paste('qsub -m n -l nodes=1:ppn=8 ',tname,sep=''))

	}
		
# Done